<template>
  <div class="map-container">
    <div id="mapContainer" class="map-wrapper"></div>
    <!-- <div class="location-info" v-if="currentLocation">
      <p>经度: {{ currentLocation.lng }}</p>
      <p>纬度: {{ currentLocation.lat }}</p>
      <p>定位时间: {{ locationTime }}</p>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { getTrajectoryPositioning } from '@/api/taskApi'
import { useRoute } from 'vue-router'

const route = useRoute()

// 定义响应式数据
const map = ref(null)
const marker = ref(null)
// const currentLocation = ref(null)
const locationTime = ref('')
let amapInstance = null
let watchPositionId = null

// 添加信息窗口引用
const infoWindow = ref(null)
const markers = ref([]) // 创建信息窗口
const createInfoWindow = () => {
  if (!infoWindow.value && amapInstance) {
    infoWindow.value = new amapInstance.InfoWindow({
      offset: new amapInstance.Pixel(0, -30),
      closeWhenClickMap: true,
      autoMove: true,
      size: new amapInstance.Size(300, 0)
    })
  }
}

// 初始化地图
const initMap = async () => {
  try {
    amapInstance = await AMapLoader.load({
      key: 'ab7c4c71dfdd6031a169ff7a4e4138f7', // 替换为你的高德地图Key
      version: '2.0',
      plugins: ['AMap.Geolocation', 'AMap.InfoWindow']
    })

    // 创建地图实例
    map.value = new amapInstance.Map('mapContainer', {
      zoom: 15,
      center: [116.397428, 39.90923] // 默认中心点（北京）
    })

    // 创建定位插件
    const geolocation = new amapInstance.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0,
      convert: true,
      showButton: true,
      buttonPosition: 'LB',
      buttonOffset: new amapInstance.Pixel(10, 20),
      showMarker: true,
      showCircle: true,
      panToLocation: true,
      zoomToAccuracy: true
    })

    map.value.addControl(geolocation)

    // 调用创建信息窗口函数
    createInfoWindow()
  } catch (error) {
    console.error('地图加载失败:', error)
  }
}

// 停止定位监听
const stopLocationWatch = () => {
  if (watchPositionId && amapInstance) {
    const geolocation = new amapInstance.Geolocation()
    geolocation.clearWatch(watchPositionId)
  }
}

// 组件挂载时初始化地图
onMounted(() => {
  initMap()
  queryTrajectoryPositioning()
})

const queryTrajectoryPositioning = async () => {
  try {
    const res = await getTrajectoryPositioning({
      orgId: route.query.orgId
    })
    if (res && res.data) {
      let position = res.data
      setTimeout(() => {
        showMultiplePositions(position)
      }, 1000)

      // 同时更新地图中心
      // if (map.value) {
      //   map.value.setCenter([res.data.longitude, res.data.latitude])
      // }
    }
  } catch (error) {
    console.error('获取获取告警详情信息失败:', error)
  }
}

// 显示多个定位点
const showMultiplePositions = (positionsData) => {
  // 清除现有标记
  markers.value.forEach((marker) => {
    if (marker) {
      marker.setMap(null)
    }
  })
  markers.value = []

  // 创建新标记
  positionsData.forEach((position, index) => {
    if (position.longitude && position.latitude) {
      const marker = new amapInstance.Marker({
        position: [position.longitude, position.latitude],
        title: position.title || `定位点${index + 1}`,
        map: map.value,
        extData: position // 这里添加extData，存储位置数据
      })

      // 添加点击事件
      marker.on('click', (e) => {
        const clickedMarker = e.target
        const positionData = clickedMarker.getExtData()
        console.log('点击的定位点数据:', clickedMarker)

        // 构建信息窗口内容
        const content = `
          <div style="padding: 10px; font-family: sans-serif;color: #333">
            <h4 style="margin: 0 0 10px 0; color: #333;">定位信息</h4>
            <p style="margin: 5px 0;"><strong>管理员:</strong> ${positionData.userName}</p>
            <p style="margin: 5px 0;"><strong>经度:</strong> ${positionData.longitude}</p>
            <p style="margin: 5px 0;"><strong>纬度:</strong> ${positionData.latitude}</p>
            ${positionData.datetime ? `<p style="margin: 5px 0;"><strong>时间:</strong> ${positionData.datetime}</p>` : ''}
            ${positionData.title ? `<p style="margin: 5px 0;"><strong>标题:</strong> ${positionData.title}</p>` : ''}
          </div>
        `

        // 设置并打开信息窗口
        infoWindow.value.setContent(content)
        infoWindow.value.open(map.value, clickedMarker.getPosition())
      })

      markers.value.push(marker)
    }
    // 调整地图视野以显示所有标记
    if (markers.value.length > 0) {
      map.value.setFitView(markers.value)
    }
  })

  // 调整地图视野以显示所有标记
  if (markers.value.length > 0) {
    map.value.setFitView(markers.value)
  }
}

// 组件卸载前清理资源
onBeforeUnmount(() => {
  stopLocationWatch()
  if (map.value) {
    map.value.destroy()
  }
  // 关闭信息窗口
  if (infoWindow.value) {
    infoWindow.value.close()
  }
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-wrapper {
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.location-info {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  z-index: 10;
}

.location-info p {
  margin: 5px 0;
  font-size: 14px;
}
</style>
